package com.yeyks.service.impl;

import com.alibaba.fastjson.JSON;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.notify.Notify;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.base.uitls.AppConditions;
import com.gexin.rp.sdk.dto.GtReq;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import com.yeyks.common.utils.ArgumentsCheckUtil;
import com.yeyks.common.utils.apputil.mqenum.TemplateType;
import com.yeyks.common.utils.apputil.type.GeTuiType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Administrator
 */
@Component
@Slf4j
public class AppGeTuiService {

    @Value("${getui.config.appId}")
    private String appId;
    @Value("${getui.config.masterSecret}")
    private String masterSecret;
    @Value("${getui.config.appKey}")
    private String appKey;
    @Value("${getui.config.url}")
    private String url;

    private IGtPush push;

    @PostConstruct
    public void init() {
        //push = new IGtPush(url, appKey, masterSecret);
        push = new IGtPush(appKey, masterSecret, false);
    }


    /**
     * 个推推送(给指定多个用户推)
     *
     * @param type 推送发送类型
     * @param clientIds 推送的集合
     * @param title     推送标题
     * @param content   推送类容
     */
    public void morePush(Integer type, List<String> clientIds, String title, String content) {
        if (clientIds == null || clientIds.size() == 0) {
            log.info("推送用户不能为空userIds[{}]", clientIds);
            return;
        }

        TransmissionTemplate template = linkTemplateDemo(type, title, content);
        ListMessage message = new ListMessage();
        //消息离线是否存储
        message.setOffline(true);
        //消息离线存储多久，单位为毫秒
        message.setOfflineExpireTime(24 * 3600 * 1000);
        //推送消息消息内容
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        //别名 或 clientId
        List<Target> targets = getTargetClientId(clientIds);
        String taskId = push.getContentId(message);
        IPushResult ret;
        try {
            ret = push.pushMessageToList(taskId, targets);
            log.info("给多个用户推{}", ret.getResponse().toString());
        } catch (RequestException e) {
            log.info("给多个用户推异常{}", e.getLocalizedMessage());
        }
    }


    /**
     * 设备Id
     *
     * @param clientIds 设备ID集合
     * @return 返回结果
     */
    private List<Target> getTargetClientId(List<String> clientIds) {
        List<Target> targets = new ArrayList<>();
        for (String clientId : clientIds) {
            Target target = new Target();
            target.setClientId(clientId);
            target.setAppId(appId);
            targets.add(target);
        }
        return targets;
    }

    private TransmissionTemplate linkTemplateDemo(Integer type, String title, String content) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionType(2);
        //内容
        template.setTransmissionContent(content);

        Notify notify = new Notify();
        if(type == GeTuiType.CREATE_ORDER){
            TemplateType templateType = JSON.parseObject(content, TemplateType.class);
            notify.setIntent("intent:#Intent;action=android.intent.action.oppopush_order;component=com.yeyks.merchant/.activity.OrderDetailActivity;S.orderNo="+
                    templateType.getData().toString()+";end");
        }else {
            notify.setIntent("intent:#Intent;action=android.intent.action.oppopush_main;component=com.yeyks.merchant/.activity.MainActivity;S.current=1;end");
        }
        notify.setTitle(title);
        notify.setContent(title);
        notify.setType(GtReq.NotifyInfo.Type._intent);
        //设置第三方的通知
        template.set3rdNotifyInfo(notify);

        APNPayload apnPayload = new APNPayload();
        apnPayload.setAutoBadge("+1");
        apnPayload.setCategory("$由客户端定义");
        //标题
        apnPayload.setAlertMsg(new APNPayload.SimpleAlertMsg(title));
        apnPayload.addCustomMsg("payload", content);
        apnPayload.addCustomMsg("mutable-content", 1);
        template.setAPNInfo(apnPayload);
        return template;
    }

    /**
     * 透传方式
     *
     * @return
     */
    private NotificationTemplate notificationTemplate(String title, String content) {

        NotificationTemplate template = new NotificationTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        Style0 style = new Style0();
        //设置通知栏信息
        // 设置通知栏标题与内容
        style.setTitle(title);
        style.setText(content);
        // 配置通知栏图标
        style.setLogo("icon.png");
        // 配置通知栏网络图标
        style.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);

        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        // 透传的内容自定义设置信息,使手机端可以判断
        template.setTransmissionContent(content);

        return template;
    }

}
